﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZR.Infrastructure.CustomException
{
    public static class FlagsEnumExtensions
    {
        /// <summary>
        /// 获取所有匹配的枚举项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="flags"></param>
        /// <returns></returns>
        public static T[] SplitToEnums<T>(this T flags) where T : Enum
        {
            return Enum.GetValues(typeof(T))
                .Cast<T>()
                .Where(e => flags.HasFlag(e))
                .ToArray();
        }

        /// <summary>
        /// 获取所有匹配的枚举项名称
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="flags"></param>
        /// <returns></returns>
        public static string[] SplitToNames<T>(this T flags) where T : Enum
        {
            return Enum.GetValues(typeof(T))
                .Cast<T>()
                .Where(e => flags.HasFlag(e))
                .Select(e => e.ToString())
                .ToArray();
        }

        /// <summary>
        /// 生成逗号分隔的字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="flags"></param>
        /// <returns></returns>
        public static string ToCombinedString<T>(this T flags) where T : Enum
        {
            return string.Join(",", flags.SplitToNames());
        }
    }
}
